<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <el-row style="display: flex; align-items: center; justify-content: space-between">
          <el-col :span="22">
            <el-radio-group v-model="viewType" @change="loadGanttData" size="mini">
              <el-radio-button label="report"><i class="el-icon-edit"></i>我负责的</el-radio-button>
              <el-radio-button label="release"><i class="el-icon-view"></i>我发布的</el-radio-button>
              <el-radio-button label="all" v-if="isShow"><i class="el-icon-aim">全部任务</i></el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="2">
            <el-button size="small" @click="releaseTasks"><i class="el-icon-plus"></i>发布任务
            </el-button>
          </el-col>
        </el-row>
      </div>
      <div ref="gantt" style="height: auto; width: 100%;"></div>
    </el-card>
    <release-tasks :releaseTaskVisible="releaseTaskVisible"
                   :releaseTaskForm="releaseTaskForm"
                   @update:releaseTaskVisible="releaseTaskVisible=$event"
                   @release="handleRelease">
    </release-tasks>


  </div>
</template>
<script>
import gantt from "dhtmlx-gantt";
import moment from 'moment';
import ReleaseTasks from "@/views/ReleaseTasks";

export default {
  name: "Task",
  components: {ReleaseTasks},
  data() {
    return {
      viewType: 'report',
      isShow: false,
      releaseTaskVisible: false,
      tasks: [],
      value: "1",
      releaseTaskForm: {
        title: '',
        categoryId: '',
        projectSn: '',
        startTime: '',
        endTime: '',
        reportBy: '',
        frequency: '周',
        contentSummaries: [{taskContentId: '', contentSummary: ''}],
        taskMilestones: [{name: '', time: ''}],
        attachment: [{taskId: '', filePath: '', source: ''}],
        reportCount: '',
      },
      dialogKey: 0,
      currentTask: {},
      taskClickEventId: null,  // 用于存储事件ID
      taskToolTipVisible: false,
    };
  },
  computed: {
    ganttConfig() {
      return this.$store.state.ganttConfig;
    }
  },
  methods: {
    resetForm() {
      this.releaseTaskForm = {
        title: '',
        categoryId: '',
        projectSn: '',
        contentSummaries: [{taskContentId: '', contentSummary: ''}],
        startTime: '',
        endTime: '',
        reportBy: '',
        frequency: '周',
        taskMilestones: [{name: '', time: ''}],
        releaseAttachments: [{taskId: '', filePath: '', source: ''}],
        reportCount: '',
      };
      this.time = [];
      this.radio1 = '是'; // 重置单选按钮的默认值
    },
    releaseTasks() {
      this.resetForm()
      this.releaseTaskVisible = true
    },
    handleRelease(data) {
      this.releaseTaskForm.startTime = moment(data.time[0]).format('YYYY/MM/DD HH:mm:ss')
      this.releaseTaskForm.endTime = moment(data.time[1]).format('YYYY/MM/DD HH:mm:ss')
      this.releaseTaskForm.reportCount = data.reportCount
      const reportBy = data.releaseTaskForm.reportBy
      // 清理空的里程碑数据
      this.releaseTaskForm.taskMilestones = this.releaseTaskForm.taskMilestones.filter(milestone =>
          milestone.name.trim() !== '' || (milestone.time && milestone.time.trim() !== '')
      );
      // 如果存在里程碑并需要格式化时间
      this.releaseTaskForm.taskMilestones = this.releaseTaskForm.taskMilestones.map(milestone => {
        return {
          ...milestone,
          time: moment(milestone.time).format('YYYY/MM/DD') // 格式化里程碑时间
        };
      });
      console.log(this.releaseTaskForm)
      const releaseTaskDTO = this.releaseTaskForm
      this.$http.post("/task/release", releaseTaskDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message({type: "success", message: `发布成功,下一步经办人:${reportBy}`, showClose: true})
          console.log(`发送任务数据:${releaseTaskDTO}`)
        } else {
          this.$message({type: "error", message: "发布失败:", showClose: true})
        }
      })
    },
    /*    selectChange(val) {
          console.log(val);
        },*/
    setupColumns() {
      const containerWidth = this.$refs.gantt.clientWidth; // 容器宽度 px

      // 定义各列百分比（总和约100%）
      const columnPercents = {
        wbs: 0.03,
        sn: 0.09,
        text: 0.42,
        report: 0.05,
        startDate: 0.08,
        endDate: 0.08,
        duration: 0.04,
        releaseBy: 0.04,
        reportBy: 0.04,
        taskStatus: 0.13
      };

      gantt.config.columns = [
        {name: "wbs", label: "wbs", width: containerWidth * columnPercents.wbs, align: 'left', template: gantt.getWBSCode},
        {name: "sn", label: "任务编号", width: containerWidth * columnPercents.sn, align: 'center', template: task => task.sn},
        {
          name: "text", label: "名称", width: containerWidth * columnPercents.text, align: 'left', tree: true, css:'grid_cell_wrap',
          template: task => {
            let badgeHtml = '';
            if (task.latestTaskCompleteApplyVO) badgeHtml += `<span class="custom-badge complete-badge">1</span>`;
            if (task.latestTaskDelayApplyVO) badgeHtml += `<span class="custom-badge delay-badge">1</span>`;
            return `<span class='title_column'>${task.text}${badgeHtml}</span>`;
          }
        },
        {name: "report", label: "汇报进度", width: containerWidth * columnPercents.report, align: "center", template: task => `${task.reportComplete}/${task.reportCount}`},
        {name: "startDate", label: "开始时间", width: containerWidth * columnPercents.startDate, align: "center", template: task => task.start_date},
        {name: "endDate", label: "结束时间", width: containerWidth * columnPercents.endDate, align: "center", template: task => task.end_date},
        {name: "duration", label: "持续", width: containerWidth * columnPercents.duration, align: "center", template: task => task.duration + " 天"},
        {name: "releaseBy", label: "发布人", width: containerWidth * columnPercents.releaseBy, align: "center", template: task => task.releaseBy},
        {name: "reportBy", label: "承担人", width: containerWidth * columnPercents.reportBy, align: "center", template: task => task.reportBy},
        {
          name: "taskStatus", label: "任务状态", width: containerWidth * columnPercents.taskStatus, align: "center",
          template: task => {
            const today = new Date();
            const start = new Date(task.start_date);
            const end = new Date(task.end_date);
            const actualEnd = task.actualFinishingTime ? new Date(task.actualFinishingTime) : null;
            const statusText = task.statusName;
            const duration = (task.duration - task.originalDuration) + 1;
            if (statusText === "已完成") {
              if (actualEnd) {
                const diffDays = Math.round((actualEnd - end) / (24 * 60 * 60 * 1000));
                if (diffDays < 0) return `已完成 - 提前 ${Math.abs(diffDays)} 天`;
                else if (diffDays > 0) return `已完成 - 延期 ${diffDays} 天`;
                else return `按时完成`;
              }
              return statusText;
            }
            if (today < start) return statusText;
            else if (statusText === "进行中") {
              const daysToEnd = Math.ceil((end - today) / (24 * 60 * 60 * 1000));
              return `${statusText} - 剩余${daysToEnd}天`;
            } else if (statusText === "申请延期") {
              const daysToEnd = Math.ceil((end - today) / (24 * 60 * 60 * 1000));
              return `${statusText} ${duration}天 - 剩余 ${daysToEnd}天`;
            } else return statusText;
          }
        }
      ];
    },
    initParentGantt() {
      const ganttConfig = this.$store.state.ganttConfig
      gantt.i18n.setLocale(ganttConfig.locale);
      gantt.config.scale_height = ganttConfig.scale_height;
      gantt.config.scales = ganttConfig.scales;
      gantt.config.xml_date = ganttConfig.xml_date;
      gantt.config.row_height = ganttConfig.row_height;
      gantt.config.show_markers = ganttConfig.show_markers;
      gantt.config.autosize = ganttConfig.autosize;
      gantt.config.readonly = ganttConfig.readonly;
      gantt.config.show_grid = ganttConfig.show_grid;
      gantt.config.min_column_width = ganttConfig.min_column_width;
      gantt.config.show_chart = ganttConfig.show_chart;
      gantt.config.open_tree_initially = true;
      gantt.templates.task_text = ganttConfig.task_text_template;
      gantt.templates.task_class = function (start, end, task) {
        if (task.hidden) {
          return "hideTask"; // 为符合条件的任务分配 "hideTask" 类
        }
        return "";
      };
      this.setupColumns();
      gantt.init(this.$refs.gantt);
      this.loadGanttData()
      this.attachTaskClickEvent();  // 绑定点击事件
    },
    attachTaskClickEvent() {
      // 先解绑之前的事件
      if (this.taskClickEventId) {
        gantt.detachEvent(this.taskClickEventId);
      }
      // 绑定新的事件
      this.taskClickEventId = gantt.attachEvent("onTaskClick", (id, e) => {
        if (e.target.classList.contains('title_column')) {
          const task = gantt.getTask(id);
          if (task) {
            task.title = task.text
            this.currentTask = task;
            console.log("选中并存储到VUEX中的任务:", this.currentTask);
            this.dialogKey++;
            this.$store.dispatch("updateCurrentTask", task)
            this.$router.push("/task_tool_tip");
          }
          return true;
        }
        return true;
      });
    },
    // 获取任务数据
    loadGanttData() {
      console.log("当前viewType:", this.viewType);
      let apiUrl;
      if (this.viewType === 'release') {
        apiUrl = "/task/ganttRelease";
      } else if (this.viewType === 'report') {
        apiUrl = "/task/ganttReport";
      } else if (this.viewType === 'all') {
        apiUrl = "/task/ganttAll";
      }
      this.$http.get(apiUrl).then((response) => {
        gantt.clearAll()
        if (response.data.code == 1) {
          const user = JSON.parse(localStorage.getItem('user'))
          const tasks = response.data.data.map(task => {
            const startDate = Date.parse(new Date(task.startTime.replace(/-/g, "/")))
            const endDate = Date.parse(new Date(task.endTime.replace(/-/g, "/")))
            let EndDateForGantt
            if (task.actualFinishingTime) {
              EndDateForGantt = Date.parse(new Date(task.actualFinishingTime.replace(/-/g, "/")))
            } else if (task.delayApprovedDate) {
              EndDateForGantt = Date.parse(new Date(task.delayApprovedDate.replace(/-/g, "/")))
            } else {
              EndDateForGantt = Date.parse(new Date(task.endTime.replace(/-/g, "/")))
            }
            const originalDuration = Math.floor((endDate - startDate) / (24 * 3600 * 1000)) + 1
            const totalDuration = Math.floor((EndDateForGantt - startDate) / (24 * 3600 * 1000)) + 1
            const progress = originalDuration / totalDuration
            return {
              id: task.id,
              sn: task.sn,
              parent: task.parentId,
              createTime: task.createTime,
              releaseBy: task.releaseBy,
              reportBy: task.reportBy,
              processInstanceId: task.processInstanceId,
              start_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(task.startTime)),
              progress: progress,
              text: task.title,
              projectSn: task.projectSn,
              frequency: task.frequency,
              statusName: task.statusName,
              reportComplete: task.reportComplete,
              reportCount: task.reportCount,
              categoryName: task.categoryName,
              originalDuration: originalDuration,
              duration: totalDuration,
              contentSummaries: task.contentSummaries,
              taskMilestones: task.taskMilestones,
              releaseAttachments: task.releaseAttachments,
              reportAttachments: task.reportAttachments,
              commentAttachments: task.commentAttachments,
              taskCommentSummaries: task.taskCommentSummaries,
              taskCompleteSummaries: task.taskCompleteSummaries,
              taskPlanSummaries: task.taskPlanSummaries,
              taskCoordinateSummaries: task.taskCoordinateSummaries,
              taskHistoryDelayVOS: task.taskHistoryDelayVOS,
              latestTaskCompleteApplyVO: task.latestTaskCompleteApplyVO,
              latestTaskDelayApplyVO: task.latestTaskDelayApplyVO
            };
          })
          tasks.forEach(task => {
            task.reportAttachments.forEach(attachment => {
              attachment.isSaved = true;  // 确认附件已保存
            });
            task.commentAttachments.forEach(attachment => {
              attachment.isSaved = true;
            })
          });
          console.log("所有任务:", tasks);
          gantt.parse({data: tasks, links: []});
          gantt.eachTask(task => {
            const hidden = task.$level === 1 && task.reportBy !== user.nickName && task.releaseBy !== user.nickName;
            console.log(`任务 ID: ${task.id}, $level: ${task.$level}, reportBy: ${task.reportBy}, releaseBy: ${task.releaseBy}, hidden: ${hidden}`);
            task.hidden = hidden; // 将 hidden 属性添加到任务对象中
          });
          gantt.sort("createTime", true)
          gantt.render();
        } else {
          console.log("任务初始化失败");
        }
      })
    }
  },
  mounted() {
    this.initParentGantt();
    const user = JSON.parse(localStorage.getItem('user'))
    if (user.username === 'mengqiang' || user.username === 'cuijin' || user.username === 'guojunshan') {
      this.isShow = true
    }
  },
  beforeDestroy() {
    if (this.taskClickEventId) {
      gantt.detachEvent(this.taskClickEventId);
    }
  },
}
</script>
<style scoped>
::v-deep .gantt_grid_head_cell {
  color: #909399;
  font-size: 0.75rem !important;
  font-family: "Helvetica Neue", "Helvetica" !important;
  font-weight: bold !important;
}
::v-deep .gantt_tree_content, .gantt_tree_icon {
  height: 100%;
  display: block;
  color: #909399;
  font-size: 0.75rem !important;
  font-family: "Helvetica Neue", "Helvetica" !important;
}
::v-deep .hideTask {
  display: none;
}
::v-deep .custom-badge {
  display: inline-block;
  padding: 0.1875rem 0.3125rem;
  margin-right: 0.3125rem;
  border-radius: 50%; /* 将边框半径设置为50%，实现圆形外观 */
  color: white;
  font-size: 0.625rem;
  text-align: center; /* 让数字在圆形内居中显示 */
  line-height: 1; /* 根据实际情况调整行高，使数字垂直居中效果更好 */
}

::v-deep .complete-badge {
  background-color: green;
}

::v-deep .delay-badge {
  background-color: #e85e5e;
}

</style>
